<?php
namespace Admin\Action;
use Common\Model;
use Common\TagLib\Dir;
class RobotsAction extends BaseAction {
	private $_tbconfig = null;
	public function _initialize() {
        parent::_initialize();
    $this->tqkuid=C('yh_app_kehuduan');
	$tkapi=trim(C('yh_api_line'));
	if(false ===$tkapi){
		$this->tqkapi = 'http://api.tuiquanke.com';
		}else{
		$this->tqkapi = $tkapi;
	}
	
$appkey=trim(C('yh_gongju'));
if(!$appkey){
$this->error('请到 站点设置  填写通行密钥',U('setting/index'));	
}else{
$this->getopenid($appkey);
}
	
	
    }
    
    
   public function pdd(){
         $where['status'] = 1;
				$where['http_mode'] = 0;
				$robots = M('pddrobots')->where($where)->order('ordid asc')->select();
			    $this->assign('list', $robots);
   	
   $this->display();
   	
   }
    
    
    
    public function index(){
				$where['status'] = 1;
				$where['http_mode'] = 0;
				$robots = M('robots')->where($where)->order('ordid asc')->select();
			    $this->assign('list', $robots);

    	
    	
    	$this->display();
    }
    
    
    
    
    
public function tuiquanke()
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/tuiquanke_collect.php';
$ret=opcache_invalidate($dir,TRUE);
}
 $tuiquanke_collect = F('tuiquanke_collect');
if(!$tuiquanke_collect || $tuiquanke_collect===false){
$page = 1;
}else{
$page =$tuiquanke_collect['page'];
 }

	    $result_data = $this->tuiquanke_collect($page);
	    if($result_data){
	    $this->assign('result_data', $result_data);
	    $resp = $this->fetch('collect');
	    $this->ajaxReturn($page==150?0:1, $page==150?'采集完成或者没有新数据了':$page+1, $resp);
	    }
	}
	
	
public function tuiquanke_pdd()
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/tuiquanke_pddcollect.php';
$ret=opcache_invalidate($dir,TRUE);
}
 $tuiquanke_collect = F('tuiquanke_pddcollect');
if(!$tuiquanke_collect || $tuiquanke_collect===false){
$page = 1;
}else{
$page =$tuiquanke_collect['page'];
 }

	    $result_data = $this->tuiquanke_collect_pdd($page);
	    if($result_data){
	    $this->assign('result_data', $result_data);
	    $resp = $this->fetch('collect');
	    $this->ajaxReturn($page==150?0:1, $page==150?'采集完成或者没有新数据了':$page+1, $resp);
	    }
	}
	
	
private function tuiquanke_collect_pdd($page)
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/tuiquanke_pddcollect.php';
$ret=opcache_invalidate($dir,TRUE);
}
$tuiquanke_collect = F('tuiquanke_pddcollect');
if(!$tuiquanke_collect || $page==1){
            $coll=0;
            $totalcoll = 0;
        }
        else{
           $coll = $tuiquanke_collect['coll'];
           $totalcoll = $tuiquanke_collect['totalcoll'];
  }
  
$file = FTX_DATA_PATH.'start_pdd.txt';
        if(!file_exists($file)){
            return false;
        }
$startId = file_get_contents($file);
        if(!$startId){
            $startId = 0;
        }
$map=array(
		'start'=>$startId,
		'pagesize'=>500,
		'time'=>time(),
		'tqk_uid'=>$this->tqkuid
);
$token=$this->create_token(trim(C('yh_gongju')),$map);
$map['token']=$token;
$url = $this->tqkapi.'/getpdditems';    
$result = $this->_curl($url,$map);
 $json = json_decode($result, true);
		 $json = $json['result'];
		 $count=count($json);
      if($count>0){
       $t=0;
       $coll=0;
      foreach ($json as $key => $val){
        $raw[] = array(
                    'goods_id'=>$val['goods_id'],
                    'goods_name'=>$val['goods_name'],
                    'goods_desc'=>$val['goods_desc'],
                    'goods_thumbnail_url'=>$val['goods_thumbnail_url'],
                    'goods_image_url'=>$val['goods_image_url'],
                    'sold_quantity'=>$val['sold_quantity'],
                    'min_group_price'=>$val['min_group_price'],
                    'min_normal_price'=>$val['min_normal_price'],
                    'mall_name'=>$val['mall_name'],
                    'category_id'=>$val['category_id']?$val['category_id']:0,
                    'coupon_discount'=>$val['coupon_discount'],
                    'coupon_total_quantity'=>$val['coupon_total_quantity'],
                     'promotion_rate'=>$val['promotion_rate'],
                    'coupon_remain_quantity'=>$val['coupon_remain_quantity'],
                    'coupon_start_time'=>$val['coupon_start_time'],
                    'coupon_end_time'=>$val['coupon_end_time'],
                    'addtime'=>$val['addtime']
                );
                
                   $startId = $val['addtime'];
                  // $res= $this->_ajax_pdd_publish_insert($raw);
                   $coll++;
                   $totalcoll++;
                   $t++;
            }
            
           M('pdditems')->addAll($raw,array(),true);	 //sus
            
          file_put_contents($file, $startId);
        }else{
       // $page=149;
        $msg="失败！";
        }

        $result_data['p']	 = $page;
        $result_data['msg']	 = $msg;
        $result_data['coll']		= $count;
        $result_data['totalcoll']	= $totalcoll;
        $result_data['totalnum']	=   $count;
        $result_data['thiscount']	= count($item);
        $result_data['times']		= time();
        F('tuiquanke_pddcollect', array(
            'coll'=>$coll, 
            'page'=>$page==150?0:$page+1,
            'totalcoll'=>$totalcoll
        ));
        return $result_data;


	}
	
private function _ajax_pdd_publish_insert($item)
    {
        $result = D('pdditems')->ajax_yh_publish($item);
        return $result;
    }
    
    
	
private function tuiquanke_collect($page)
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/tuiquanke_collect.php';
$ret=opcache_invalidate($dir,TRUE);
}
$tuiquanke_collect = F('tuiquanke_collect');
if(!$tuiquanke_collect || $page==1){
            $coll=0;
            $totalcoll = 0;
        }
        else{
           $coll = $tuiquanke_collect['coll'];
           $totalcoll = $tuiquanke_collect['totalcoll'];
  }
  
$file = FTX_DATA_PATH.'start.txt';
        if(!file_exists($file)){
            return false;
        }
$startId = file_get_contents($file);
        if(!$startId){
            $startId = 0;
        }
$map=array(
		'start'=>$startId,
		'pagesize'=>500,
		'time'=>time(),
		'tqk_uid'=>$this->tqkuid
);
$token=$this->create_token(trim(C('yh_gongju')),$map);
$map['token']=$token;
$url = $this->tqkapi.'/getitems';
$result = $this->_curl($url,$map);
 $json = json_decode($result, true);
		 $PID= $json['pid'];
		 $json = $json['result'];
		 $count=count($json);
      if($count>0){
       $t=0;
       $coll=0;
      foreach ($json as $key => $val){
        if(C('yh_site_secret')==1 && false === strpos($attach, 'https://')){
		$pic_url=str_replace("http://","https://",$val['pic_url']);
		}else{
		$pic_url=$val['pic_url'];
		}
		 $link = 'https://item.taobao.com/item.htm?id=' . $val['num_iid'];
		 
                $raw[]=array(
                'link'=>$link,
		        'click_url'=>'',
		        'pic_url'=>$pic_url,
		        'title'=>$val['title'],
		        'tags'=>$val['tags'],
		        'coupon_start_time'=>$val['coupon_start_time'],
		        'add_time'=>strtotime(date('Y-m-d H:i:s')),
		        'coupon_end_time'=>$val['coupon_end_time'],
		        'ali_id'=>$val['ali_id'],
		        'cate_id'=>$val['cate_id'],
		        'shop_name'=>$val['shop_name'],
		        'shop_type'=>$val['shop_type'],
		        'ems'=>1,
		        'num_iid'=>$val['num_iid'],
	           // 'sellerId'=>$tbdetail['sellerid'],
	             //'volume'=>$tbdetail['volume'],
		        'volume'=>$val['volume'],
		        'commission'=>$val['commission'],
		        'tuisong'=>0,
		        'area'=>0,
		        'pass'=>1,
		        'status'=>'underway',
		        'isshow'=>1,
		       // 'commission_rate'=>'',
                'commission_rate' =>$val['tk_commission_rate'], //佣金比例
		        'tk_commission_rate'=>$val['tk_commission_rate'],
		        'sellerId'=>$val['sellerId'],
		        'nick'=>$val['nick'],
		        'mobilezk'=>0,
		        'hits'=>0,
		        'price'=>$val['price'],
		        'coupon_price'=>$val['coupon_price'],
		        'coupon_rate'=>$val['coupon_rate']?$val['coupon_rate']:0,
		        'intro'=>$val['intro'],
		        'up_time'=>$val['up_time'],
		        'desc'=>'',
		        'isq'=>'1',
		        'quanurl'=>'https://uland.taobao.com/coupon/edetail?activityId='.$val['Quan_id'].'&itemId='.$val['num_iid'].'&pid='. $PID .'',
		        'quan'=>$val['quan'],
		        'Quan_id'=>$val['Quan_id'],
		        'Quan_condition'=>0,
		        'Quan_surplus'=>$val['Quan_surplus']?$val['Quan_surplus']:0,
                'Quan_receive'=>$val['Quan_receive']?$val['Quan_receive']:0,
                'is_commend'=>$val['is_commend']?$val['is_commend']:0
                );
                
                
                
                 $startId = $val['id'];
                 // $res= $this->_ajax_yh_publish_insert($raw);
                   $coll++;
                  $totalcoll++;
                  $t++;
            }
           M('items')->addAll($raw,array(),true);	//fail
            
          file_put_contents($file, $startId);
        }else{
     //   $page=149;
        $msg="失败！";
        }

        $result_data['p']	 = $page;
        $result_data['msg']	 = $msg;
        $result_data['coll']		= $count;
        $result_data['totalcoll']	= $totalcoll;
        $result_data['totalnum']	=   $count;
        $result_data['thiscount']	= count($item);
        $result_data['times']		= time();
        F('tuiquanke_collect', array(
            'coll'=>$coll, 
            'page'=>$page==150?0:$page+1,
            'totalcoll'=>$totalcoll
        ));
        return $result_data;


	}
	
	
	
	
	
	
   private function _ajax_yh_publish_insert($item)
    {
        $result = D('items')->ajax_yh_publish($item);
        return $result;
    }   
    
    
public function collect(){
		$id	= I('id','','intval');
		$auto	= I('auto',0,'intval');
		$p		= I('p',1,'intval');

$where=array(
'id'=>$id
);
$date = M('robots')->field('tb_cid',true)->where($where)->find();
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/robot_setting.php';
$ret=opcache_invalidate($dir,TRUE);
}
F('robot_setting', $date);
		
if($date){
	
if($date['http_mode'] == '0'){
	
if ($p > $date['page']) {
		
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/totalcoll.php';
$ret=opcache_invalidate($dir,TRUE);
}
					F('totalcoll', NULL);
					$this->ajaxReturn(0, '已经采集完成'.$date['page'].'页！请返回，谢谢');
}
				
               $result_data = $this->api_collect($date,$p);
				$this->assign('result_data', $result_data);
			    $resp = $this->fetch('collect');
				if($result_data['coll'] <= 0){
				    $this->ajaxReturn(0, '已经采集完成！请返回，谢谢',$resp);
				}
			
				$this->ajaxReturn(1, '', $resp);
			}
			
		}else{
			$this->ajaxReturn(0, 'error');
		}
	}

public function api_collect($date,$p)
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/totalcoll.php';
$dir2=$basedir.'/data/Runtime/Data/robots_time.php';
$ret=opcache_invalidate($dir,TRUE);
$ret=opcache_invalidate($dir2,TRUE);
}
M('robots')->where(array('id'=>$date['id']))->save(array('last_page'=>$p,'last_time'=>time()));
		if (false === $totalcoll = F('totalcoll')) {
			$totalcoll = 0;
		}
		if (false === $robots_time = F('robots_time')) {
			$robots_time = time();
			F('robots_time', time());
		}
		 $cate = array();
		 if($date['cate_id']){
		    $cate = M('itemscate')->field('ali_id,id')->where(array('id'=>$date['cate_id']))->find();
		 }
$appkey=trim(C('yh_taobao_appkey'));
$appsecret=trim(C('yh_taobao_appsecret'));
$apppid=trim(C('yh_taobao_pid'));
$apppid=explode('_', $apppid);
$AdzoneId=$apppid[3];
if(!empty($appkey) && !empty($appsecret) && !empty($AdzoneId)){
vendor("taobao.taobao");
$c = new \TopClient();
$c->appkey = $appkey;
$c->secretKey = $appsecret;
$req = new \TbkDgMaterialOptionalRequest();
$req->setPageSize("100");
$req->setPageNo("".$p."");
$req->setPlatform("1");
$req->setIsOverseas("true");
$req->setCat($date['keyword']);
$req->setHasCoupon("true");
$req->setAdzoneId($AdzoneId);
$resp = $c->execute($req);
$resp = json_decode(json_encode($resp), true);
$datares=$resp['result_list']['map_data'];
}

if($datares){		
	$t=0;
	  $coll=0;
	$now=time();
		foreach ($datares as $key => $val){
		$link = 'https://item.taobao.com/item.htm?id=' . $val['num_iid'];
		if(!empty($val['coupon_id']) && !empty($val['seller_id'])){ 
            $receive = $val['coupon_total_count'];
//          $preg1 = '/减(.+?)元/is';
//			preg_match($preg1, $val['coupon_info'], $allhtml1);
//			$coupon_price=$allhtml1[1];
            $coupon_price = $val['coupon_amount'];
            $pic_url = str_replace('http://', 'https://', $val['pict_url']);
            $pic_url = str_replace('_400x400', '', $pic_url);
		    $raw[] = array(
		        'link'=>$link,
		        'click_url'=>'',
		        'pic_url'=>$pic_url,
		        'title'=>$val['title'],
		        'coupon_start_time'=>NOW_TIME,
		        'add_time'=>strtotime(date('Y-m-d H:i:s')),
		        'coupon_end_time'=>strtotime($val['coupon_end_time']),
		        'ali_id'=>$cate['ali_id'],
		        'cate_id'=>$cate['id'],
		        'shop_name'=>$val['shop_title'],
		        'shop_type'=>$val['user_type']==1?'B':'C',
		        'ems'=>1,
		        'num_iid'=>$val['num_iid'],
		        'volume'=>$val['volume'],
		        'commission'=>$val['commission_rate'],
		        'tuisong'=>0,
		        'pass'=>1,
		        'status'=>'underway',
		        'isshow'=>1,
		        'commission_rate'=>$val['commission_rate'],
		        'tk_commission_rate'=>$val['commission_rate'],
		        'sellerId'=>$val['seller_id'],
		        'nick'=>'0',
                'area'=>0,
		        'mobilezk'=>0,
		        'hits'=>0,
		        'price'=>$val['zk_final_price'],
		        'coupon_price'=>$val['zk_final_price']-$coupon_price,
		        'coupon_rate'=>intval(($val['zk_final_price']-$coupon_price)/$val['zk_final_price']*100*100),
		        'intro'=>'',
		        'up_time'=>$now+$t,
		        'desc'=>'',
		        'isq'=>'1',
		        'quanurl'=>$val['coupon_share_url'],
		        'quan'=>$coupon_price,
		        'Quan_id'=>$val['coupon_id'],
		        'Quan_condition'=>0,
		        'Quan_surplus'=>$receive*10,
		        'Quan_receive'=>$receive
		    );
           // $res= $this->_ajax_yh_publish_insert($raw);
             $coll++;
             $totalcoll++;
            	}


		    $thiscount++;
			$t++;
		}
		
  M('items')->addAll($raw,array(),true);	


if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/totalcoll.php';
$ret=opcache_invalidate($dir,TRUE);
}
F('totalcoll',$totalcoll);
if($sus=='no'){
 $p = $date['page']+1; 
}

}else{
$p=499;
}
		
		$result_data['p']			= $p;
		$result_data['msg']			= $msg;
		$result_data['coll']		    = $coll;
		$result_data['totalcoll']	= $totalcoll;
		$result_data['totalnum']  	=   $totalnum;
		$result_data['thiscount']	= $thiscount;
		$result_data['times']		= lefttime(time()-$robots_time);
		return $result_data;
		
		
}  
    
    
    
    

}